/**
 * @author Steve Sedlmayr
 * @mail ssedlmayr@gmail.com
 * @link http://code.google.com/p/chitin/
 * @version 0.1
 
	The MIT License

	Copyright (c) 2009 Steve Sedlmayr

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/

package srs.chitin 
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.utils.getDefinitionByName;
	import flash.utils.getQualifiedClassName;
	
	import srs.chitin.data.LocalDataDelegate;
	import srs.chitin.data.SharedStateDelegate;
	import srs.chitin.module.extensible.OutboundEvent;
	import srs.chitin.mvstate.base.ModelBase;
	import srs.chitin.mvstate.base.ViewBase;
	import srs.chitin.mvstate.extensible.StateChangeEvent;
	import srs.chitin.mvstate.extensible.View;
	import srs.chitin.mvstate.implementation.MetaStateChangeEvent;
	import srs.chitin.mvstate.implementation.ModelStateChangeEvent;
	import srs.chitin.util.implementation.vo.VOUtil;
	
	public class AS3ShellApplication extends Sprite implements IShellApplication {
		protected var _persistModelToDisk:Boolean = false;
		
		public function get persistModelToDisk() : Boolean {
			return this._persistModelToDisk;
		}
		
		public function set persistModelToDisk(value:Boolean) : void {
			this._persistModelToDisk = value;
		}
		
		[ArrayElementType("srs.chitin.ViewInstantiationVO")]
		protected var _viewConfigurationList:Array;
		
		[ArrayElementType("srs.chitin.mvstate.extensible.View")]
		protected var _viewList:Array;
		
		/* BEGIN Model */
			
		private var _shellModelVO:ShellModelVO = new ShellModelVO();
		
		public function get shellModelVO() : ShellModelVO {
			return this._shellModelVO;
		}
		
		private var _shellModel:ShellModel = ShellModel.getInstance();
		
		public function get shellModel() : ShellModel {
			return this._shellModel;
		}
		
		/* END Model */
		
		public function AS3ShellApplication() {
			if ( this._persistModelToDisk ) {
				LocalDataDelegate.setSharedObject("local.data");
				SharedStateDelegate.setSharedObject("shared.data");
			}
			
			addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler, false, 0, true);
		}
		
		public function getOutboundEventHandler() : Function {
			return outboundEventHandler;
		}
		
		protected function populateViewList() : void {
			//Override this method in a subclass and provide an implementation as follows.
			/*this._viewList = [this._oneView as View, this._anotherView];
			this._viewConfigurationList = [
				new ViewInstantiationVO(anURL, aParentSprite, this), //This one is a ModuleDelegateView, so it takes a URL and an application reference.
				new ViewInstantiationVO("", anotherParentSprite, null, "show", [this._viewList[0]], [AModelClass, AnotherModelClass])
			];*/
		}
		
		private final function instantiateViews() : void {
			var currentConfiguration:ViewInstantiationVO;
			var currentDefinition:Object;
			var instanceName:String;
			var qualifiedClassName:String;
			var unqualifedClassName:String;
			var viewListIndex:uint = 0;
			
			for each ( var view:View in this._viewList ) {
				currentConfiguration = this._viewConfigurationList[viewListIndex];
				qualifiedClassName = getQualifiedClassName(view);
				currentDefinition = getDefinitionByName(qualifiedClassName);
				unqualifedClassName = qualifiedClassName.split("::")[1];
				instanceName = unqualifedClassName.substring(0, 1).toLowerCase() + unqualifedClassName.substring(1, unqualifedClassName.length);
				
				view.name = instanceName;
				view.addEventListener(StateChangeEvent.STATE_CHANGE_EVENT, stateChangeEventHandler, false, 0, true);
				
				if ( view is ModuleDelegateView ) {
					(view as ModuleDelegateView).url = currentConfiguration.url;
					(view as ModuleDelegateView).application = this;
				}
				
				addModelsToView(currentConfiguration, view);
				addViewsToView(currentConfiguration, view);
				performAdditionalViewOperations(currentConfiguration, view);
				
				view[currentConfiguration.initialBehavior](view);
				if ( currentConfiguration.attachmentTarget != null ) { currentConfiguration.attachmentTarget.addChild(view); }
				
				++viewListIndex;
			}
			
			handleViewsInstantiated();
		}
		
		protected function handleViewsInstantiated() : void {}
		
		protected function addModelsToView(configuration:ViewInstantiationVO, view:View) : void {
			var currentDefinition:Object;
			var instanceName:String;
			var qualifiedClassName:String;
			var unqualifedClassName:String;
			
			for each ( var modelDefinition:Class in configuration.getModels ) {
				qualifiedClassName = getQualifiedClassName(modelDefinition);
				currentDefinition = getDefinitionByName(qualifiedClassName);
				unqualifedClassName = qualifiedClassName.split("::")[1];
				instanceName = unqualifedClassName.substring(0, 1).toLowerCase() + unqualifedClassName.substring(1, unqualifedClassName.length);
				
				view.addModel((modelDefinition["getInstance"]() as ModelBase), instanceName);
			}
		}
		
		protected function addViewsToView(configuration:ViewInstantiationVO, view:View) : void {
			var currentDefinition:Object;
			var instanceName:String;
			var qualifiedClassName:String;
			var unqualifedClassName:String;
			
			for each ( var viewInstance:ViewBase in configuration.getViews ) {
				qualifiedClassName = getQualifiedClassName(viewInstance);
				currentDefinition = getDefinitionByName(qualifiedClassName);
				unqualifedClassName = qualifiedClassName.split("::")[1];
				instanceName = unqualifedClassName.substring(0, 1).toLowerCase() + unqualifedClassName.substring(1, unqualifedClassName.length);
				
				view.addView(viewInstance, instanceName);
			}
		}
		
		protected function performAdditionalViewOperations(configuration:ViewInstantiationVO, view:View) : void {}
		
		/* Store all values in a local VO for reference; we do this any time 
		   fields are updated from a module or a shell-level view. */ 
		private function updateModelVO(vo:*, changed:Array=null) : void {
			/* TO-DO :: modify the handling of the second to last flag 
			   to be able to handle both values */
			//Update the VO and SharedObject.
			VOUtil.clone(vo, this._shellModelVO, true, true, changed);
			if ( this._persistModelToDisk ) { saveModelToSharedObject(); }
		}
		
		//Store all values in a SharedObject here.
		protected function saveModelToSharedObject() : void {
			var enumeration:Array = this._shellModelVO.getEnumeration();
			var enumerationIndex:uint = 0;
			
			while ( enumerationIndex < enumeration.length ) {
				var property:* = VOUtil.getProperty(ShellModelVO, enumeration[enumerationIndex]);
				
				LocalDataDelegate.save(enumeration[enumerationIndex], property); //Application data.
				SharedStateDelegate.save(enumeration[enumerationIndex], property); //Shared application state.
				
				++enumerationIndex;
			}
		}
		
		protected function handleOutboundEvent(event:Event) : void {}
		
		protected function handleStateChangeEvent(event:Event) : void {}
		
		private final function addedToStageHandler(event:Event) : void {
			populateViewList();
			instantiateViews();
			
			removeEventListener(Event.ADDED_TO_STAGE, addedToStageHandler, false);
		}
		
		//Outbound events from the modules.
		private function outboundEventHandler(event:OutboundEvent) : void {
			//If a outboundNotificationVO member is present, update the shell's model.
			if ( event.outboundNotificationVO != null ) { updateModelVO(event.outboundNotificationVO, event.changed); }
			handleOutboundEvent(event);
		}
		
		private function stateChangeEventHandler(event:StateChangeEvent) : void {
			if ( event is MetaStateChangeEvent ) {
				handleStateChangeEvent(event);
			}
			
			/* Handle ModelStateChangeEvents - these update the shell's model from 
			   its views' models in the same way outboundEventHandler does from 
			   its modules' models. */
			if ( event is ModelStateChangeEvent ) {
				updateModelVO(event["outboundNotificationVO"]); //If an outboundNotificationVO member is present, update the shell's model.
			}
		}
	}
}